<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('新建处方信息')"/>
    <th:block th:include="include :: datetimepicker-css"/>
    <style>
        .drug-item {
            border: 2px solid #000;
            text-align: center;
            padding: 10px;
            margin: 5px 10px;
            font-weight: 700;
            font-size: 16px;
            border-radius: 5px;
            color: #000;
        }

        .scroll-pane-top {
            max-height: 40px;
            overflow-y: scroll;
            overflow-x: hidden;
        }

        #scroll-pane-bottom {
            overflow-y: scroll;
            overflow-x: hidden;
        }

        .patient-info {
            margin: 5px 0px;
        }

        .hand {
            cursor: pointer;
        }

        .nostock {
            background-color: #f0e6e6;
        }
    </style>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <div class="container-div">
        <div class="row">
            <div class="col-sm-8">
                <form class="form-horizontal m" id="form-records-add" th:object="${tPrescriptionRecords}">
                    <input name="id" th:field="*{id}" type="hidden">
                    <div class="form-group scroll-pane-top">
                        <div class="row patient-info">
                            <div class="col-sm-6">
                                <label class="col-sm-3 control-label is-required">姓名：</label>
                                <div class="col-sm-3">
                                    <input name="name" id="name" th:field="*{name}" th:readonly="${mode}=='detail'"
                                           class="form-control" type="text" required>
                                </div>
                                <input id="crtime" name="crtime" th:field="*{crtime}" type="hidden" >
                                <label class="col-sm-3 control-label is-required">性别：</label>
                                <div class="col-sm-3">
                                    <select name="sex" id="sex" class="form-control" th:readonly="${mode}=='detail'"
                                            th:with="type=${@dict.getType('sys_user_sex')}" onchange="change()">
                                        <option th:each="dict : ${type}" th:text="${dict.dictLabel}"
                                                th:value="${dict.dictValue}" th:field="*{sex}"></option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <label class="col-sm-3 control-label is-required">年龄：</label>
                                <div class="col-sm-3">
                                    <input name="age" th:field="*{age}" id="age" th:readonly="${mode}=='detail'"
                                           class="form-control" type="number" required>
                                </div>
                                <label class="col-sm-3 control-label">皮试结果：</label>
                                <div class="col-sm-3">
                                    <input th:field="*{skinTest}" readonly class="form-control">
                                </div>
                            </div>
                        </div>
                        <div class="row patient-info">
                            <label class="col-sm-2 control-label">电话：</label>
                            <div class="col-sm-3">
                                <input name="phone" th:field="*{phone}" th:readonly="${mode}=='detail'"
                                       class="form-control" type="text">
                            </div>

                            <label class="col-sm-2 control-label">身份证号：</label>
                            <div class="col-sm-3">
                                <input name="idNumber" th:field="*{idNumber}" th:readonly="${mode}=='detail'"
                                       class="form-control" type="text"
                                       onchange="idNumber_change()">
                            </div>
                        </div>
                        <div class="row patient-info">
                            <label class="col-sm-2 control-label">住址：</label>
                            <div class="col-sm-10">
                                <input name="address" th:field="*{address}" th:readonly="${mode}=='detail'"
                                       class="form-control" type="text">
                            </div>
                        </div>
                        <div class="row patient-info">
                            <label class="col-sm-2 control-label">诊断：</label>
                            <div class="col-sm-10">
                                <textarea name="diagnosis" class="form-control" th:readonly="${mode}=='detail'">[[*{diagnosis}]]</textarea>
                            </div>
                        </div>
                    </div>
                    <div class="row" th:if="${mode!='detail'}">
                        <div class="col-sm-5">
                            <input name="seach_keywords" id="seach_keywords" class="form-control" type="text"
                                   placeholder="请输入药品名或者别名" search="search">
                        </div>
                        <button type="button" class="btn btn-white btn-sm" onclick="search_drug()"><i
                                class="fa fa-search">搜索</i>
                        </button>
                        <a class="btn btn-white btn-sm" onclick="search_reset()"><i class="fa fa-refresh"></i>&nbsp;重置</a>

                        <a href="#cfxq" class="pull-right col-sm-1 btn btn-white btn-sm">处方详情</a>
                        <a href="#business_qt" class="pull-right col-sm-1 btn btn-white btn-sm">其他</a>
                        <a href="#business_fzsl" class="pull-right col-sm-1 btn btn-white btn-sm">非注射类</a>
                        <a href="#business_zsl" class="pull-right col-sm-1 btn btn-white btn-sm">注射类</a>
                    </div>

                    <div id="scroll-pane-bottom">
                        <div class="row">
                            <div class="col-sm-12">
                                <div class="col-sm-12" id="zsl-html"></div>
                                <div class="col-sm-12" id="fzsl-html"></div>
                                <div class="col-sm-12" id="qt-html"></div>
                                <div class="col-sm-12 select-table table-striped">
                                    <a name="cfxq"></a>
                                    <table id="bootstrap-table" data-use-row-attr-func="true"
                                           data-reorderable-rows="true"></table>
                                </div>
                            </div>
                        </div>
                        <div class="row" style="margin-top: 10px">
                            <div class="col-sm-12">
                                <div class="col-sm-9"></div>
                                <div id="zsje" class="col-sm-3" style="display: none">注射金额:</div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-sm-12">
                                <div class="col-sm-9"></div>
                                <div id="ypje" class="col-sm-3" style="display: none">药品金额:</div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-sm-12">
                                <div class="col-sm-9"></div>
                                <div id="zje" class="col-sm-3" style="display: none">总金额:</div>
                            </div>
                        </div>
                        <a class="btn btn-info btn-rounded btn-sm" onclick="getSettlementList()"><i
                                class="fa fa-book"></i>结算清单</a>
                    </div>
                </form>
            </div>
            <div class="col-sm-4">
                <div class="col-sm-6 pull-right" th:if="${mode!='detail'}">
                    <div class="input-group">
                        <input type="number" class="form-control" id="days" placeholder="用药天数" evnt="changeDays">
                        <span class="input-group-btn">
                                            <button class="btn btn-default" type="button" style="padding:5px 12px;"
                                                    onclick="setAllDays()">Go!</button>
                                        </span>
                    </div>
                </div>
                <div class="col-sm-4 select-table table-striped">
                    <table id="bootstrap-table2" data-use-row-attr-func="true"
                           data-reorderable-rows="true"></table>
                </div>
                <div class="col-sm-6" style="float: right;">
                    <div id="zje2" style="display: none;padding:10px;">总金额:</div>
                </div>
            </div>
            <div class="row" th:if="${mode=='detail'}">
                <div class="col-sm-8">
                    <div class="col-sm-2">操作人</div>
                    <div class="col-sm-2">医生</div>
                    <div class="col-sm-2">药房</div>
                    <div class="col-sm-2">护士</div>
                </div>
            </div>
            <div class="row" th:if="${mode=='detail'}" th:object="${tPrescriptionRecords}">
                <div class="col-sm-8">
                    <div class="col-sm-2"></div>
                    <div class="col-sm-2">[[*{doctorName}]]</div>
                    <div class="col-sm-2">[[*{pharmacyName}]]</div>
                    <div class="col-sm-2">[[*{nurseName}]]</div>
                </div>
            </div>
        </div>
    </div>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: datetimepicker-js"/>
<script th:src="@{/js/common.js}"></script>
<script th:if="${mode!='detail'}"
        th:src="@{/ajax/libs/bootstrap-table/extensions/reorder-rows/bootstrap-table-reorder-rows.js}"></script>
<script th:if="${mode!='detail'}"
        th:src="@{/ajax/libs/bootstrap-table/extensions/reorder-rows/jquery.tablednd.js}"></script>
<script th:inline="javascript">
    var prefix = ctx + "system/records"

    var mode = [[${mode}]];
    // 是否为详情页面
    var isDetail = mode == "detail";
    // 禁用的属性内容
    var readonlyStr = isDetail ? "readonly" : ""
    // 药品分类
    var drugTypes = [[${@dict.getType('sys_drug_type')}]];
    // 注射类的子类
    var business_zsl = [[${@dict.getType('business_zsl')}]];
    // 非注射类的子类
    var business_fzsl = [[${@dict.getType('business_fzsl')}]];
    // 其他类的子类
    var business_qt = [[${@dict.getType('business_qt')}]];

    $("#form-records-add").validate({
        focusCleanup: true
    });

    function dateFormat(date, format){
        date = new Date(date);
        date.setHours(date.getHours() - 14);
        var dset = {
            "M+": date.getMonth() + 1, // 月
            "d+": date.getDate(), // 日
            "H+": date.getHours(), // 时
            "m+": date.getMinutes(), // 分
            "s+": date.getSeconds(), // 秒
            "q+": Math.floor((date.getMonth() + 3) / 3), // 刻钟
            S: date.getMilliseconds(), // 毫秒
        };

        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        }

        for (var i in dset) {
            if (new RegExp("(" + i + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? dset[i] : ("00" + dset[i]).substr(("" + dset[i]).length));
            }
        }
        return format;
    }


    function getSettlementList() {
        var _xbdate  = dateFormat($("#crtime").val(),'yyyy-MM-dd HH:mm:ss')
        // console.log(_xbdate);
        $.ajax({
            url: prefix + "/getSettlementList",
            type: 'post',

            data: {
                crtime: _xbdate,
                name: $("#name").val(),
                sex: $("#sex").val(),
                age: $("#age").val(),

            },
            dataType: 'json',
        }).then((res) => {
            if(res.msg === '操作成功'){
                $.modal.alertWarning("结算清单导出成功");
                $.modal.enable();
                $.modal.closeLoading();
            }
        })
    }

    function submitHandler() {
        if ($.validate.form()) {
            let para = ""
            var id = document.getElementsByName("id")[0].value;
            if (id == "") {
                id = 0;
            }
            para += $.common.sprintf("id=%s", id)
            para += $.common.sprintf("&name=%s", encodeURI(document.getElementsByName("name")[0].value))
            para += $.common.sprintf("&sex=%s", encodeURI(document.getElementsByName("sex")[0].value))
            para += $.common.sprintf("&age=%s", encodeURI(document.getElementsByName("age")[0].value))
            para += $.common.sprintf("&phone=%s", encodeURI(document.getElementsByName("phone")[0].value))
            para += $.common.sprintf("&address=%s", encodeURI(document.getElementsByName("address")[0].value))
            para += $.common.sprintf("&diagnosis=%s", encodeURI(document.getElementsByName("diagnosis")[0].value))
            para += $.common.sprintf("&idNumber=%s", encodeURI(document.getElementsByName("idNumber")[0].value))
            if (document.getElementsByName("skinTest").length > 0) {
                para += $.common.sprintf("&skinTest=%s", encodeURI(document.getElementsByName("skinTest")[0].value))
            }
            // para += $.common.sprintf("&zsAmount=%s", tmpSyf)
            // para += $.common.sprintf("&drugAmount=%s", drug_amount)
            para += $.common.sprintf("&totalAmount=%s", total_amount)

            chufang_drugs.forEach((item, index) => {
                para += $.common.sprintf("&tPrescriptionDrugInfoList[%s].prescriptionid=%s", index, id);
                para += $.common.sprintf("&tPrescriptionDrugInfoList[%s].days=%s", index, item.days);
                para += $.common.sprintf("&tPrescriptionDrugInfoList[%s].counts=%s", index, item.counts);
                para += $.common.sprintf("&tPrescriptionDrugInfoList[%s].remarks=%s", index, encodeURI(item.remarks));
                para += $.common.sprintf("&tPrescriptionDrugInfoList[%s].drugid=%s", index, item.drugid);
                para += $.common.sprintf("&tPrescriptionDrugInfoList[%s].drugPrice=%s", index, item.drugPrice);
                para += $.common.sprintf("&tPrescriptionDrugInfoList[%s].amount=%s", index, item.amount);
                para += $.common.sprintf("&tPrescriptionDrugInfoList[%s].drugName=%s", index, encodeURI(item.drugName));
                para += $.common.sprintf("&tPrescriptionDrugInfoList[%s].drugType=%s", index, item.drugType);
                para += $.common.sprintf("&tPrescriptionDrugInfoList[%s].drugSpecs=%s", index, item.drugSpecs);
            });

            if (mode == "add") {
                $.operate.save(prefix + "/add", para);
            } else if (mode == "edit") {
                $.operate.save(prefix + "/edit", para);
            }
        }
    }

    $("input[name='crtime']").datetimepicker({
        format: "yyyy-mm-dd",
        minView: "month",
        autoclose: true
    });

    // 输液费，固定值
    // var syf = 0;

    // 处方的药品信息
    var chufang_drugs = [[${tPrescriptionRecords.tPrescriptionDrugInfoList}]] || [];

    var options = {
        id: "bootstrap-table",
        pagination: false,
        showSearch: false,
        showRefresh: false,
        showToggle: false,
        showColumns: false,
        sidePagination: "client",
        //data: chufang_drugs,
        onReorderRow: function (data) {
            //当拖拽结束后，data为整个表格的数据
            // 当sidePagination: "server"时，拖拽行后顺序错乱，需要重新调用加载数据方法
            chufang_drugs = data;
            refresh_tabledata();
            return false;
        },
        columns: [
            {
                field: 'index',
                title: '序号',
                visible: true, //隐藏后，无法删除行
                formatter: function (value, row, index) {
                    return row.index = index + 1; //返回行号
                }
            },
            {
                field: 'drugName',
                align: 'center',
                title: '名称'
            },
            {
                field: 'drugType',
                align: 'center',
                title: '分类',
                formatter: function (value, row, index) {
                    return $.table.selectDictLabel(drugTypes, value);
                }
            },
            {
                field: 'drugPrice',
                align: 'center',
                title: '零售价'
            },
            {
                field: 'drugSpecs',
                align: 'center',
                title: '规格'
            },
            {
                field: 'counts',
                align: 'center',
                title: '用药数量',
                width: 40,
                formatter: function (value, row, index) {
                    return $.common.sprintf("<input class='form-control' type='number' min='0' max='9999' step='1' %s name='tPrescriptionDrugInfoList[%s].counts' value='%s' onchange=\"cell_change(%s,'counts')\">", readonlyStr, index, value, index
                    )
                        ;
                }
            },
            {
                field: 'days',
                align: 'center',
                title: '用药天数',
                width: 40,
                formatter: function (value, row, index) {
                    return $.common.sprintf("<input class='form-control' type='number' min='0' max='9999' step='1' %s name='tPrescriptionDrugInfoList[%s].days' value='%s' onchange=\"cell_change(%s,'days')\">", readonlyStr, index, value, index);
                }
            },
            {
                field: 'amount',
                align: 'center',
                title: '合计金额'
            },
            {
                field: 'remarks',
                align: 'center',
                title: '备注',
                width: 80,
                formatter: function (value, row, index) {
                    return $.common.sprintf("<input class='form-control' type='text' %s name='tPrescriptionDrugInfoList[%s].remarks' value='%s' onchange=\"cell_change(%s,'remarks')\">", readonlyStr, index, value, index);
                }
            },
            {
                title: '操作',
                align: 'center',
                visible: !isDetail,
                formatter: function (value, row, index) {
                    var value = $.common.isNotEmpty(row.index) ? row.index : $.table.serialNumber(index);
                    return '<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="removeRow(' + value + ')"><i class="fa fa-remove"></i>删除</a>';
                }
            }],
    };

    var options2 = {
        id: "bootstrap-table2",
        pagination: false,
        showSearch: false,
        showRefresh: false,
        showToggle: false,
        showColumns: false,
        sidePagination: "client",
        columns: [
            {
                field: 'drugName',
                align: 'center',
                title: '名称'
            },
            {
                field: 'drugSpecs',
                align: 'center',
                title: '规格'
            },
            {
                field: 'counts',
                align: 'center',
                title: '用药数量',
                width: 40,
                formatter: function (value, row, index) {
                    return $.common.sprintf("<input class='form-control' type='number' min='0' max='9999' step='1' %s name='tPrescriptionDrugInfoList[%s].counts' value='%s' onchange=\"cell_change(%s,'counts')\">", readonlyStr, index, value, index
                    )
                        ;
                }
            },
            {
                field: 'days',
                align: 'center',
                title: '用药天数',
                width: 40,
                formatter: function (value, row, index) {
                    return $.common.sprintf("<input class='form-control' type='number' min='0' max='9999' step='1' %s name='tPrescriptionDrugInfoList[%s].days' value='%s' onchange=\"cell_change(%s,'days')\">", readonlyStr, index, value, index);
                }
            },
            {
                title: '操作',
                align: 'center',
                visible: !isDetail,
                formatter: function (value, row, index) {
                    var value = $.common.isNotEmpty(row.index) ? row.index : $.table.serialNumber(index);
                    return '<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="removeRow(' + value + ')"><i class="fa fa-remove"></i>删除</a>';
                }
            }
        ],
    };

    $(function () {
        // getSYF()
        $.table.init(options);
        $.table.init(options2);
        refresh_tabledata();
        // 获取数据字典内容
        // let syfInfo = [[${syf}]];
        // if (syfInfo == null) {
        //     $.modal.alertError('获取输液费失败')
        // } else {
        //     syf = syfInfo.retailPrice / 100;
        // }
        updateZje()

        $("input[evnt='changeDays']").keydown(function (event) {
            if (event.keyCode == 13) {
                setAllDays();
            }
        });

        if (mode == "add" || mode == "edit")
            search_drug();
        if (mode == "add")
            $("#scroll-pane-bottom").css("max-height", (window.screen.availHeight - 354) + "px");
        else if (mode == "edit")
            $("#scroll-pane-bottom").css("max-height", (window.screen.availHeight - 364) + "px");
        else if (mode == "detail")
            $("#scroll-pane-bottom").css("max-height", (window.screen.availHeight - 374) + "px");
    });


    function refresh_tabledata() {
        $("#bootstrap-table").bootstrapTable("load", chufang_drugs);
        $("#bootstrap-table2").bootstrapTable("load", chufang_drugs);
    }

    // 搜索出来的药品信息
    var drugList = []

    function search_drug() {
        drugList = [];
        $("#zsl-html").html("");
        $("#fzsl-html").html("");
        $("#qt-html").html("");
        var keywords = $("#seach_keywords").val().trim();
        // if (keywords == "") {
        //     return
        // }

        $.ajax({
            url: '/business/drugInfo/list',
            type: 'post',
            // 设置的是请求参数
            data: {
                pageSize: 999999,
                pageNum: 1,
                isAsc: "asc",
                drugName: keywords,
            },
            dataType: 'json', // 用于设置响应体的类型 注意 跟 data 参数没关系！！！
            success: function (res) {
                // 一旦设置的 dataType 选项，就不再关心 服务端 响应的 Content-Type 了
                // 客户端会主观认为服务端返回的就是 JSON 格式的字符串

                for (let i = 0; i < res.length; i++) {
                    res[i].drugPrice = res[i].drugPrice / 100
                }

                res.rows.forEach(item => {
                    item.retailPrice = item.retailPrice / 100
                })
                drugList = res.rows;

                let html = "";
                for (let i = 0; i < drugTypes.length; i++) {
                    // 药品类型（注射类/非注射类/其他）
                    let drugTypeInfo = drugTypes[i];
                    // 药品类型下的所有药品
                    let drugTypeDrugs = drugList.filter(a => a.drugType == drugTypeInfo.dictValue)
                    if (drugTypeDrugs.length > 0) {
                        html += `<div class="col-sm-12"><h3>${drugTypeInfo.dictLabel}<a href=\"\" name=\"${drugTypeInfo.dictValue}\"></a></h3></div>`;

                        // 药品子类（抗生素注射液/抗菌消炎药等）
                        var drugCategoryList = [];
                        if (drugTypeInfo.dictValue == "business_zsl")
                            drugCategoryList = business_zsl;
                        else if (drugTypeInfo.dictValue == "business_fzsl")
                            drugCategoryList = business_fzsl;
                        else
                            drugCategoryList = business_qt;

                        drugCategoryList.forEach(category => {
                            // 子类中的所有药品
                            var drugItems = drugTypeDrugs.filter(a => a.drugCategory == category.dictValue)
                            if (drugItems.length > 0) {
                                html += `<div class="col-sm-12"><h4>${category.dictLabel}<a href=\"\" name=\"${category.dictValue}\"></a></h4></div>`;
                                drugItems.forEach(drug => {
                                    drug.drugTypeStr = drugTypeInfo.dictLabel;
                                    drug.drugCategoryStr = category.dictLabel
                                    let nameLimit6 = drug.drugName
                                    if (drug.drugName.length > 6) {
                                        nameLimit6 = drug.drugName.substring(0, 6) + "...";
                                    }
                                    //点击事件，添加药品到处方
                                    let onclick = ""
                                    //无库存的样式
                                    let nostockcss = ""
                                    if (drug.stock > 0) {
                                        onclick = `onclick="drug_click('${drug.id}')"`
                                    } else {
                                        nostockcss = "nostock"
                                    }
                                    html += `<div class="col-sm-2 drug-item mt3-l hand ${nostockcss}" ${onclick} title="${drug.drugName}"
                             data-toggle="tooltip" data-placement="top">
                            <span>${nameLimit6}</span><br/><span>${drug.drugSpecs}</span>
                        </div>`
                                })
                            }
                        })
                    }
                }
                $("#zsl-html").html(html)
                $("[data-toggle='tooltip']").tooltip();
            }
        });
    }

    function drug_click(drugid) {
        let drugItem = drugList.find(a => a.id == drugid)
        if (drugItem == undefined) {
            return;
        }
        // 用药数量默认值
        let defaultCount = 1
        // 用药天数默认值
        let defaultDays = 1
        chufang_drugs.push({
            drugid: drugItem.id,
            drugName: drugItem.drugName,
            drugType: drugItem.drugType,
            drugTypeStr: drugItem.drugTypeStr,
            drugPrice: drugItem.retailPrice,
            drugSpecs: drugItem.drugSpecs,
            counts: defaultCount,
            days: defaultDays,
            amount: Number(drugItem.retailPrice * defaultCount.toFixed(2)),
            remarks: "",
        });

        updateZje();
        refresh_tabledata();
    }

    /* 删除指定表格行 */
    function removeRow(index) {
        chufang_drugs.splice(index - 1, 1);
        updateZje();
        refresh_tabledata();
    }

    // 当前输液费
    // let tmpSyf = [[${tPrescriptionRecords.zsAmount}]];
    // 药品总金额
    let drug_amount = [[${tPrescriptionRecords.drugAmount}]];
    // 处方总金额
    let total_amount = [[${tPrescriptionRecords.totalAmount}]];

    // 更新总金额
    function updateZje() {
        let zslDrugs = chufang_drugs.filter(a => a.drugType == "business_zsl");
        if (zslDrugs.length > 0) {
            let days = zslDrugs.map(a => {
                return a.days
            })
            // let maxDay = Math.max(...days)
            // tmpSyf = syf * maxDay;
            // $("#zsje").css("display", "block").text("注射金额：" + tmpSyf);
        } else {
            // tmpSyf = 0;
            // $("#zsje").css("display", "none");
        }
        // drug_amount = 0;
        total_amount = 0;
        chufang_drugs.forEach(a => total_amount += a.amount);
        // total_amount = tmpSyf + drug_amount;

        // $("#ypje").css("display", "block").text("药品金额：" + drug_amount);
        $("#zje").css("display", "block").text("总金额：" + total_amount);
        $("#zje2").css("display", "block").text("总金额：" + total_amount);
    }

    function cell_change(rowindex, colName) {
        let value = event.target.value
        var rowData = chufang_drugs[rowindex]

        if (rowData[colName] == value) {
            return
        }

        // 字段赋新值
        rowData[colName] = value
        // 计算总金额
        if (colName == "counts") {
            rowData["amount"] = Number((value * rowData["drugPrice"] * rowData["days"]).toFixed(2))
            updateZje();
        } else if (colName == "days") {
            rowData["amount"] = Number((value * rowData["drugPrice"] * rowData["counts"]).toFixed(2))
            updateZje();
        }
        refresh_tabledata();
    }

    function idNumber_change() {
        let value = event.target.value.trim();
        if (value.length != 18)
            return;

        let birthday = value.substr(6, 8)
        let year = birthday.substr(0, 4)
        let month = birthday.substr(4, 2)
        let day = birthday.substr(6, 2)
        let birthdate = new Date(year, month - 1, day)
        var age = Math.floor((new Date() - birthdate) / (1 * 24 * 60 * 60 * 1000) / 365);
        $("#age").val(age)
    }


    function setAllDays() {
        var str = $("#days").val().trim();
        if (!/^\d+$/.test(str)) {
            $.modal.msgError("请输入一个整数");
            return
        }
        var day = Number(str);
        chufang_drugs.forEach(item => {
            item.days = day;
            item.amount = item.drugPrice * item.counts * item.days;
        })
        updateZje();
        refresh_tabledata();
    }


    function mysearch() {
        search_drug();
    }

    function search_reset() {
        $("#seach_keywords").val("");
    }
</script>
</body>
</html>